<template>
  <div v-loading="loading">
    <el-table ref="goodsTable" :data="tableData" highlight-current-row size="mini" border :show-summary="showSummary"
      :summary-method="getSummaries">
      <el-table-column type="index" width="50" align="center"> </el-table-column>
      <template v-for="col  in tableColumns">
        <el-table-column :key="col.prop" :label="col.label" :prop="col.prop" show-overflow-tooltip :width="col.width"
          :min-width="col.minWidth || 120">
          <template v-slot:header>
            <span v-if="col.required" style="color:red">*</span>
            <span>{{ col.label }}</span>
          </template>
          <template slot-scope="scope">
            <!-- 附件 -->
            <l-upload-preview v-if="col.dataType == 'image'" v-model="scope.row[col.prop]" :placeholder="$t('请输入')"
              :limit="3" listType="picture-card" :disabled="!scope.row.isEditing">
            </l-upload-preview>
            <!-- 下拉选择 -->
            <l-select v-else-if="col.dataType == 'dataItem'" :options="options[col.dataCode]"
              :class="{ noBorder: !scope.row.isEditing }" v-model="scope.row[col.prop]" size="mini"
              :disabled="!scope.row.isEditing" :placeholder="scope.row.isEditing ? `请选择` : ``"></l-select>

            <l-tree-select v-else-if="col.dataType == 'treeSelect'" :options="options[col.dataCode]" :parent="false"
              :class="{ noBorder: !scope.row.isEditing }" v-model="scope.row[col.prop]" size="mini"
              :disabled="!scope.row.isEditing" :placeholder="scope.row.isEditing ? `请选择` : ``"></l-tree-select>

            <l-select v-else-if="col.dataType == 'contract-select'" :options="col.options" v-model="scope.row[col.prop]"
              :class="{ noBorder: !scope.row.isEditing }" size="mini" :disabled="!scope.row.isEditing"
              :placeholder="scope.row.isEditing ? `请选择` : ``"
              @change="(e) => handleChange(e, scope.row, col.filed)"></l-select>

            <!-- 创建用户 -->
            <l-createuser v-else-if="col.dataType == 'createuser'" size="mini" v-model="scope.row[col.prop]"
              :class="{ noBorder: !scope.row.isEditing }" />
            <!-- 更新时间 -->
            <l-modifytime v-else-if="col.dataType == 'modifytime'" size="mini" v-model="scope.row[col.prop]"
              :class="{ noBorder: !scope.row.isEditing }" />

            <template v-else-if="!scope.row.isEditing">
              <span v-if="col.dataType == 'datetime'">{{ lr_dateFormat(scope.row[col.prop], 'yyyy-MM-dd') }}</span>
              <span v-else-if="col.dataType == 'switch'">{{ scope.row[col.prop] ? '是' : '否' }}</span>
              <span v-else>{{ scope.row[col.prop] }}</span>
            </template>
            <template v-else>
              <l-date v-if="col.dataType == 'datetime'" v-model="scope.row[col.prop]" :format="col.format"
                :placeholder="$t('请选择')" size="mini"></l-date>
              <el-switch v-else-if="col.dataType == 'switch'" :active-value="true" :inactive-value="false"
                v-model="scope.row[col.prop]">
              </el-switch>
              <el-input v-else v-model="scope.row[col.prop]" size="mini" :placeholder="$t('请输入')"></el-input>
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="100" v-if="!readonly">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.isEditing" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-else type="text" size="small" @click="handleSave(scope.row)">保存</el-button>
          <el-button v-if="hasRemove" @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          <slot v-bind="scope" name="btns"></slot>
        </template>
      </el-table-column>
    </el-table>
    <div class="l-edit-table--addbtn" v-if="!readonly" @click="handleAdd()">
      <el-button type="text" size="mini" icon="el-icon-plus">新增一行</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "l-table-edit",
  props: {
    tableColumns: {
      type: Array,
      default: () => []
    },
    tableData: {
      type: Array,
      default: () => []
    },
    required: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    hasRemove: {
      type: Boolean,
      default: true,
    },
    showSummary: {
      type: Boolean,
      default: false,
    },
    summaryMethod: Function,
  },
  data() {
    return {
      options: {},
      loading: true,
    };
  },
  watch: {
    tableData() {
      this.$nextTick(() => {
        this.$refs.goodsTable.doLayout()
      })
    }
  },
  computed: {

  },
  mounted() {
    this.init()
  },
  methods: {
    handleChange(e, data, filed) {
      console.log(e);
      data[filed] = e?.contractType
    },
    init() {
      // 获取数据字典
      this.tableColumns.forEach(t => {
        if (t.dataType == 'dataItem' || t.dataType == 'radio') {
          if (!this.options[t.dataCode]) {
            this.options[t.dataCode] = []
            this.options[t.dataCode] = this.lr_dataItemOptions(this.lr_dataItem[t.dataCode])
          }
        }
        if (t.dataType == 'treeSelect') {
          this.options[t.dataCode] = []
          const data = this.lr_dataItemOptions(this.lr_dataItem[t.dataCode])
          this.options[t.dataCode] = this.lr_dataItemTree(
            data,
            "f_ItemValue",
            "f_ItemName"
          );
        }
      })
      setTimeout(() => {
        this.loading = false
      }, 1000);

    },
    // 删除
    async handleDelete(row) {
      this.$emit('table', { type: 'delete', data: row })
    },
    // 打开编辑
    handleEdit(row) {
      if (this.ishaveEdit()) {
        row.isEditing = true
        this.$forceUpdate();
      }
    },
    // 关闭编辑
    handleCloseEdit(row) {
      row.isEditing = false
      this.$forceUpdate();
    },
    // 保存
    async handleSave(row) {
      if (this.validate()) {
        this.$emit('table', { type: 'save', data: row })
      }
    },
    // 新增一行
    handleAdd() {
      if (this.ishaveEdit()) {
        this.$emit('table', { type: 'push' })
      }
    },

    // 判断当前table是否存在编辑项
    ishaveEdit() {
      const result = this.tableData.every(item => item.isEditing === false)
      if (result) {
        return true
      } else {
        this.$message({
          type: 'error',
          message: '当前有未保存的数据，请保存后再操作'
        })
        return false
      }
    },
    // 校验
    validate() {
      let res = true
      if (this.required) {
        if (this.tableData.length == 0) {
          this.$message({
            type: 'error',
            message: this.$t(`请添加表格数据`)
          })
          return false
        }
      }
      try {
        this.tableData.forEach((row, index) => {
          this.tableColumns.forEach(col => {
            if (col.required && this.$validatenull(row[col.prop])) {
              this.$message({
                type: 'error',
                message: this.$t(`请输入第${index + 1}行-${col.label}`)
              })
              res = false
              throw new Error()
            }
          })
        })
      } catch (error) {
        console.log("🚀🚗 ~ validate ~ error:", error)
      }
      return res
    },

    // 表尾部 统计
    getSummaries(param) {
      if (this.summaryMethod) {
        return this.summaryMethod(param);
      }
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }

        const myColumn = this.tableColumns.find((t) => t.prop == column.property);

        if (myColumn && myColumn.isSummary) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = "";
          }
        } else {
          sums[index] = " ";
        }
      });
      return sums;
    },

  }
};
</script>
<style lang="scss" scoped>
::v-deep .noBorder {
  .el-input__inner {
    background-color: #fff0 !important;
    border-color: #ffffff00 !important;
  }

  .el-input__suffix-inner {
    display: none;
  }
}
</style>